package com.nit.lab.service.basic.impl;

import cn.hutool.core.date.DateTime;
import com.nit.lab.dto.basic.GoodsDTO;
import com.nit.lab.dto.basic.GoodsListDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.GoodsEntity;
import com.nit.lab.entity.basic.GoodsListEntity;
import com.nit.lab.mapper.basic.GoodsListMapper;
import com.nit.lab.mapper.basic.GoodsMapper;
import com.nit.lab.service.basic.GoodsListService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsListServiceImpl implements GoodsListService {


    @Autowired(required = false)
    private GoodsListMapper goodsListMapper;
    @Resource
    private GoodsMapper goodsMapper;


    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = goodsListMapper.count4Table(
                tableReqDTO.parseQueryParam("goodsName"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                goodsListMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("goodsName"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()
                ));
//        for(int i=0;i<pagingDTO.getData().size();i++){
//            GoodsDTO goodsDTO =  (GoodsDTO) pagingDTO.getData().get(i);
//            if(goodsDTO.getCreator2()==null)
//            {
//                goodsDTO.setCreator2(goodsDTO.getCreator());
//            }
//            if(goodsDTO.getOwner2()==null){
//                goodsDTO.setOwner2(goodsDTO.getOwner());
//            }
//            pagingDTO.getData().set(i,(Object) goodsDTO);
//        }
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(GoodsListDTO goodsListDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        GoodsListEntity goodsListEntity = mapperFactory.getMapperFacade().map(goodsListDTO, GoodsListEntity.class);
        return goodsListMapper.update(goodsListEntity);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove1(String ids) throws Exception {
        String[] arrayGoodsId = ids.split(",");
        for (int i = 0; i < arrayGoodsId.length; i++) {
            System.out.println(arrayGoodsId[i]);
            System.out.println(Long.parseLong(arrayGoodsId[i]));
            goodsListMapper.remove1(Long.parseLong(arrayGoodsId[i]));
        }
        return arrayGoodsId.length;
    }


    @Override
    public Integer add(GoodsListDTO goodsListDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        GoodsListEntity goodsListEntity = mapperFactory.getMapperFacade().map(goodsListDTO, GoodsListEntity.class);
        return  goodsListMapper.add(goodsListEntity);
    }

    /**
     * @description: 获取主表页面商品信息
     * @Author: ZB
     * @Date: 2022/7/14 0:47
     **/
    @Override
    public List<GoodsListDTO> listGoodsData() throws Exception {
        try {
            List<GoodsListDTO> list = goodsListMapper.listGoodsData();
            for (GoodsListDTO goodsListDTO : list) {
                String startId = goodsMapper.getInfo(goodsListDTO.getListId(), 1).getHashId();
                goodsListDTO.setStartId(startId);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<GoodsDTO> getGoods(String listIds) throws Exception{
        String[] list = listIds.split(",");
        List<GoodsDTO> goodsIds = new ArrayList<>();
        for (String s : list) {
            goodsIds.addAll(goodsListMapper.getGoodsId(Integer.parseInt(s)));
        }
        return goodsIds;
    }

    @Override
    public Long getNum(Long startId) throws Exception {
        return goodsListMapper.getNum(startId);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<GoodsListDTO> getGoodsInfo(String listId) throws Exception {
        try {
            List<GoodsListDTO> list = goodsListMapper.getGoodsInfo(Integer.parseInt(listId));
            for (GoodsListDTO goodsListDTO : list) {
                String startId = goodsMapper.getInfo(Integer.parseInt(listId), 1).getHashId();
                goodsListDTO.setStartId(startId);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<GoodsDTO> getBasicGoodsInfo(String hashId) throws Exception {
        try {
            List<GoodsDTO> list = goodsListMapper.getBasicGoodsInfo(hashId);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @description: 购买，如果都被预定了返回null，前端提示下
     * @Author: WJM
     * @Date: 2022/7/14 0:47
     **/
    // 在5个商品里面删的时候商品数量不会减1
    @Override
    public List<GoodsEntity> buy(Integer listId) throws Exception {
        List<GoodsEntity> goodsEntities = new ArrayList<>();
        Date showTime = goodsListMapper.getShowTime(listId);
        Date date = new Date();
        if(date.after(showTime)){
            Integer number = goodsListMapper.getGoodsNum(listId);
            for(int i=number; i>=1; i--){
                Integer status = goodsMapper.getStatusById(listId, number);
                if(status == 0){
                    goodsEntities.add(goodsMapper.getInfo(listId, number));
                    goodsMapper.updateStatus(listId, number, 1);
                    goodsListMapper.dropNum(listId);
                    break;
                }
            }
            if(!CollectionUtils.isEmpty(goodsEntities))
                return goodsEntities;
            else
                return null;
        } else
            return null;
    }
    /**
     * @description: 商品已购买后对数据库里的商品进行更改，num=0的商品不予展示
     * @Author: WJM
     * @Date: 2022/7/14 0:48
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String bought(String status, Integer goodsId, String owner) throws Exception {
        GoodsEntity goodsEntity = goodsMapper.getById(goodsId);
        if(status.equals("true")){
    //      goodsListMapper.dropNum(Long.parseLong(s), 1);
            goodsEntity.setModifyTime(new DateTime());
            goodsEntity.setOwner(owner);
            goodsMapper.update2(goodsEntity);
            return "true";
        } else{
            goodsMapper.updateStatus(goodsEntity.getListId(), goodsEntity.getGoodsNumber(), 0);
            goodsListMapper.addNum(goodsEntity.getListId(), 1);
            return "false";
        }
    }

    @Override
    public Integer editStatus(Integer id) throws Exception {
        return goodsListMapper.editStatus(id);
    }

    @Override
    public List<GoodsEntity> getAllGoods(Integer goodsId) throws Exception{
        List<GoodsEntity> goodsEntities = goodsMapper.all(goodsId);
        for (GoodsEntity goodsEntity : goodsEntities) {
            goodsEntity.setHashId(DigestUtils.md5DigestAsHex(goodsEntity.getGoodsId().toString().getBytes(StandardCharsets.UTF_8)));
            goodsMapper.updateAll(goodsEntity);
        }
        return goodsMapper.all(goodsId);
    }
}
